<template>
  <div class="login-container">
    <div class="login-header">
      <h1 class="login-title">DHI考试系统</h1>
      <p class="login-subtitle">使用手机号登录</p>
    </div>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="phone"
          name="phone"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请输入密码' }]"
        />
      </van-cell-group>

      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="loading"
        >
          登录
        </van-button>
        <div class="login-options">
          <van-button
            class="register-btn"
            text="注册账号"
            type="primary"
            @click="goToRegister"
          >
          </van-button>
        </div>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";

import { showToast } from "vant";
import { useRoute, useRouter } from "vue-router";

import { useUserStore } from "../../stores/user";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const phone = ref("");
const password = ref("");
const loading = ref(false);

// 提交表单
const onSubmit = async () => {
  loading.value = true;
  try {
    await userStore.login({ phone: phone.value, password: password.value });
    showToast("登录成功");
    const redirect = (route.query.redirect as string) || "/home";
    router.replace(redirect);
  } catch (error: any) {
    console.error("登录失败", error);
    showToast(error?.message || "登录失败，请检查手机号和密码");
  } finally {
    loading.value = false;
  }
};

const goToRegister = () => {
  router.push("/register");
};
</script>

<style scoped>
.login-container {
  padding: 30px 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #323233;
}

.login-subtitle {
  font-size: 16px;
  color: #969799;
  margin: 0;
}

.login-options {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

.register-btn {
  font-size: 14px;
}
</style>
